/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2024-11-05
 * Time: 22:46
 */
public class test4 {
    /*
    LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
    给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。

    如果数组中不存在目标值 target，返回 [-1, -1]。
     */

    public int[] searchRange(int[] nums, int target) {
        int leftIndex = binarySearch(nums,target,true);
        int rightIndex = binarySearch(nums,target,false)-1;
        if(leftIndex<=rightIndex && rightIndex< nums.length && nums[leftIndex] == target
                && nums[rightIndex]==target){
            return new int[] {leftIndex,rightIndex};
        }
        return new int[]{-1,-1};
    }

    public int binarySearch(int [] nums,int target,boolean lower){
        int left=0;
        int ans =nums.length;
        int right=nums.length-1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(nums[mid]>target || (lower && nums[mid]>=target)){
                right=mid-1;
                ans=mid;
            }else{
                left=mid+1;
            }
        }
        return ans;
    }
}
